package zheezes.eisp.collect.model.impl.gbw;

import java.math.BigDecimal;
import java.util.Calendar;

import org.apache.log4j.Logger;

import zheezes.eisp.collect.model.SummatorDailyFrozenCollectTaskHandler;
import zheezes.eisp.data.orm.CollectTask;
import zheezes.eisp.data.orm.Proportion;
import zheezes.eisp.data.orm.Summator;
import zheezes.eisp.data.orm.SummatorDailyFrozenData;
import zheezes.protocol.Frame;
import zheezes.protocol.impl.gbw.DataUnit;
import zheezes.protocol.impl.gbw.GbwConAddr;
import zheezes.protocol.impl.gbw.GbwFrame;
import zheezes.protocol.impl.gbw.afn0d.Afn0DDownF1DataUnit;
import zheezes.protocol.impl.gbw.afn0d.Afn0DUpF1DataUnit;
import zheezes.protocol.impl.gbw.format.DataForm20;
import zheezes.socket.Transput;


public class GbwSummatorDailyFrozenCollectTaskHandler extends SummatorDailyFrozenCollectTaskHandler {
	private static Logger logger = Logger.getLogger(GbwSummatorDailyFrozenCollectTaskHandler.class);
	
	static {
		logger.debug(String.format("load %s", GbwSummatorDailyFrozenCollectTaskHandler.class.getName()));
	}

	public void run() {
		GbwConAddr con = new GbwConAddr(dataAccessor.getConById(task.getConId()).getLogicAddr());
		Calendar cal = Calendar.getInstance();
		cal.setTime(task.getDataDate());
		Summator sm = dataAccessor.getSummatorByCon(task.getConId());
		SummatorDailyFrozenData smdf = dataAccessor.querySummatorDailyFrozenDataByMpIdAndDate(sm.getMpId(), cal.getTime());
		if(smdf == null) {
			GbwFrame frame = new GbwFrame();
			frame.setDirection(GbwFrame.DIRECTION_DOWN);
			frame.setPrm(GbwFrame.PRM_STARTUP);
			frame.setConcentrator(con);
			frame.setAfn((byte) 0x0D);
			Afn0DDownF1DataUnit du = new Afn0DDownF1DataUnit();
			DataForm20 df = new DataForm20();
			df.setDate(cal);
			du.setDate(df);
			frame.addDataUnit(du);

			// mailbox.clear();
			Transput transput;
			if ((transput = postOffice.send(frame)) != null) {
				Frame[] recv = null;
				if (transput.await() == Transput.SUCCESS && (recv = transput.getRecv()) != null) {
					// Object message = null;
					for (Frame message : recv) {
					// while((message = mailbox.get()) != null) {
						if (save((GbwFrame) message, sm) == 0) {
							task.setCollectedNum(1);
							task.setStatus(CollectTask.STATUS_FINISH);
							checkSummatorDailyUse(sm, cal);
						}
					}
				}
			}
			task.setRunTimes(task.getRunTimes() + 1);
		} else {
			task.setStatus(CollectTask.STATUS_FINISH);
		}
		task.setLastRunDate(Calendar.getInstance().getTime());
		dataAccessor.updateCollectTask(task);
	}

	private int save(GbwFrame frame, Summator sm) {
		Proportion cp = dataAccessor.getProportionById(sm.getCp());
		Proportion tp = dataAccessor.getProportionById(sm.getTp());
		if (frame.getAfn() == (byte) 0x0D && frame.getDataUnits().length > 0) {
			for (DataUnit du : frame.getDataUnits()) {
				if (du.hasData()) {
					Afn0DUpF1DataUnit unit = (Afn0DUpF1DataUnit) du;
					SummatorDailyFrozenData smdf = new SummatorDailyFrozenData();
					smdf.setDate(unit.getFdate().getDate().getTime());
					smdf.setMpId(sm.getMpId());
					BigDecimal pp = unit.getActiveEnergy().getValue();
					BigDecimal pq = unit.getReactiveEnergy().getValue();
					if (pp != null || pq != null) {
						if (pp != null) {
							smdf.setPp(pp.multiply(cp.getValue()).multiply(tp.getValue()));
						}
						if (pq != null) {
							smdf.setPq(pq.multiply(cp.getValue()).multiply(tp.getValue()));
						}
						return dataAccessor.saveSummatorDailyFrozenData(smdf);
					}
				}
			}
		}
		return -1;
	}
}
